//
//  RecordViewController.swift
//  MMTest
//
//  Created by liujianlong on 2022/9/19.
//

import UIKit

class RecordViewController: EPViewController {
    var nodataview = UIView(frame: CGRect(x: 0, y: 0, width: kUIScreenWidth, height: kUIScreenHeight - 200))
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initUI()
        self.loadData()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.view.sendSubviewToBack(self.tableView)
    }
    override func initUI() {
        self.title = LS("历史记录")
        
        let img = UIImageView(image: UIImage(named: "设备搜索中备份"))
        img.cornerRadius = 20
        self.nodataview.isHidden = true
        self.nodataview.addSubview(img)
        img.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: kUIScreenWidth - 120, height: kUIScreenWidth - 120))
            make.centerX.centerY.equalToSuperview()
        }
        
        self.tableViewStyle = .grouped
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.tableHeaderView = UIView(frame: .zero)
        weak var weakself = self
        self.tableView.refreshBlock = { refresh in
            weakself?.loadData()
        }
        self.tableView.register(RecordCell.nib(), forCellReuseIdentifier: RecordCell.ID())
        self.tableView.snp.makeConstraints { make in
            make.left.right.top.bottom.equalToSuperview().inset(20)
        }
    }
    
    var array = [Record](){
        didSet{
            self.nodataview.isHidden = array.count > 0
            self.tableView.tableFooterView =  self.nodataview.isHidden ? UIView(frame: .zero) : self.nodataview
            self.tableView.reloadData()
        }
    }
    var localArray = [Record](){
        didSet{
            self.array = self.localArray + self.netArray
        }
    }
    var netArray = [Record](){
        didSet{
            self.array = self.localArray + self.netArray
        }
    }
    
    //MARK: - 导出记录
    func actionForBtn(_ record : Record) {
        let content = UserDefaults.standard.value(forKey:localEmailKey) as? String ?? defaultEmail
        EPAlertPopViewController.pop(LS("请输入接收邮箱"), content, .input) { tag ,text in
            record.email = text?.count ?? 0 > 0 ? text! : content
            RLHud.start("正在导出")
            NetworkTool.download(record) {
                DispatchQueue.main.async {
                    UserDefaults.standard.setValue(record.email, forKey: localEmailKey)
                    self.loadData()
                }
            }
        }
    }
    
    
    func loadData(){
        
        let str = String(format:"where %@=%@", bg_sqlKey("noUpload"),bg_sqlValue("1"))
        Record.bg_findAsync(nil, where:str) { result in
            DispatchQueue.main.async {
                self.localArray = result as? [Record] ?? [Record]()
                self.tableView.mj_header?.endRefreshing()
            }
        }
        
        let str2 = String(format:"where %@=%@", bg_sqlKey("noUpload"),bg_sqlValue("0"))
        Record.bg_findAsync(nil, where:str2) { result in
            DispatchQueue.main.async {
                self.netArray = result as? [Record] ?? [Record]()
                self.tableView.mj_header?.endRefreshing()
            }
        }
        
        NetworkTool.request(EPApi.history(self.deviceUUID())) { response in
            let code = (response.value(forKey: "code") as? NSNumber ?? NSNumber(value: 0)).intValue
            if code == 200{
                let data = response.value(forKey:"data") as? NSArray ?? NSArray()
                self.netArray = Record.mj_objectArray(withKeyValuesArray: data) as? [Record] ?? [Record]()
                if self.netArray.count > 0 {
                    Record.bg_saveOrUpdateArrayAsync(self.netArray)
                }
                self.tableView.mj_header?.endRefreshing()
            }
        }
        
    }
    
}

//MARK: - UITableViewDataSource
extension RecordViewController : UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.array.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: RecordCell.ID()) as! RecordCell
        cell.model = self.array[indexPath.section]
        weak var weakself = self
        cell.block = {
            weakself?.actionForBtn((weakself?.array[indexPath.section])!)
        }
        return cell
        
    }
    
    
}
//MARK: - UITableViewDelegate
extension RecordViewController : UITableViewDelegate{
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = .clear
        return view
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
}
